package com.retailcloud.thirdpartyservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.retailcloud.commonutils.exception.RetailCloudException;
import com.retailcloud.commonutils.utils.RedisUtils;
import com.retailcloud.thirdpartyservice.service.MessageService;
import com.retailcloud.thirdpartyservice.utils.MessageUtil;
import com.retailcloud.thirdpartyservice.utils.SmsCodeGeneratorUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wudi
 * @date 2024/11/6
 * @comment
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    MessageUtil messageUtil;
    @Resource
    RedisUtils redisUtils;

    @Override
    public void sendMessage(String phoneNumber) {

        String smsCode = SmsCodeGeneratorUtil.generateSmsCode();
        Map<String, String> map = new HashMap<>();
        map.put("code", smsCode);

        String code = redisUtils.get("smsCode:" + phoneNumber);
        if (StringUtils.isNotBlank(code)) {
            throw new RetailCloudException("短信验证码已发送，请勿重复发送，有效时长5分钟", 5001);
        }
        //存入redis ,5分钟有效期
        redisUtils.set("smsCode:" + phoneNumber, smsCode, 60 * 5);

        messageUtil.sendMessage(phoneNumber, JSONObject.toJSONString(map));
    }
}
